package com.njcb.ams.service;

import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.repository.dao.SysParamDAO;
import com.njcb.ams.repository.entity.SysParam;
import com.njcb.ams.repository.entity.SysParamExample;
import com.njcb.ams.util.AmsAssert;
import com.njcb.ams.util.AmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ParamManageService{

	@Autowired
	private SysParamDAO sysParamDAO;

	public static ParamManageService getInstance() {
		return AppContext.getBean(ParamManageService.class);
	}
	
	public List<SysParam> queryAll() {
		List<SysParam> paramList = sysParamDAO.selectAll();
		return paramList;
	}

	public List<SysParam> queryParam(SysParam sysParam) {
		List<SysParam> paramList = sysParamDAO.selectBySelective(sysParam);
		return paramList;
	}

	@CacheEvict(value = "SysParamCache", key = "sysParam_?", allEntries = true)
	public int saveSysParam(SysParam sysParam) {
		AmsAssert.notNull(sysParam.getName(), sysParam.getValue(), "参数名和参数值不能为空");
		if(AmsUtils.isNull(sysParam.getId())){
			SysParam orgSysParam = sysParamDAO.getSysParamByName(sysParam.getName());
			AmsAssert.isNull(orgSysParam, "参数名[" + sysParam.getName() + "]已存在");
			return sysParamDAO.insert(sysParam);
		}else{
			return sysParamDAO.updateByPrimaryKey(sysParam);
		}
	}

	@CacheEvict(value = "SysParamCache", key = "sysParam_?", allEntries = true)
	public int deleteSysParam(String name) {
		AmsAssert.notNull(name, "参数名和参数值不能为空");
		SysParamExample example = new SysParamExample();
		SysParamExample.Criteria c = example.createCriteria();
		c.andNameEqualTo(name);
		return sysParamDAO.deleteByExample(example);
	}

	@CacheEvict(value = "SysParamCache", key = "sysParam_?", allEntries = true)
	public void updateParam(List<SysParam> insertList, List<SysParam> deleteList, List<SysParam> updateList) {
		for (int i = 0; i < insertList.size(); i++) {
			SysParam in = insertList.get(i);
			sysParamDAO.insert(in);
		}
		for (int i = 0; i < deleteList.size(); i++) {
			SysParam del = deleteList.get(i);
			sysParamDAO.deleteByPrimaryKey(del.getId());
		}
		for (int i = 0; i < updateList.size(); i++) {
			SysParam upd = updateList.get(i);
			sysParamDAO.updateByPrimaryKey(upd);
		}
	}

	// 根据名称获取对应值
	@Cacheable(value = "SysParamCache", key = "'sysParam_'+#name")
	public String getValueByName(String name) {
		String value = sysParamDAO.getValueByName(name);
		return value;
	}


}
